/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.dao.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import com.mr.qa.bo.User;

/**
 * Data access object (DAO) for domain model class User.
 * @see .User
 */
public class UserDAO extends BaseHibernateDAO 
{

    private static final Log log = LogFactory.getLog(UserDAO.class);

	//property constants
	public static final String LOGIN_NAME = "loginName";
	public static final String PASSWORD = "password";
	public static final String NAME = "name";
	public static final String SIGNATURE = "signature";
	public static final String MOBILE = "mobile";
	public static final String EMAIL = "email";
	public static final String STATE = "state";
	public static final String TYPE = "type";

    public List getList()
    {
        try 
        {
            Query queryObject = getSession().createQuery("from User as model order by model.type desc,model.isSuper desc,model.id");//2008.7.2
            //System.out.println("pageNo="+this.getPageNo()+",RecordCount="+this.getRecordCount());
            if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0)
            {
                queryObject.setFirstResult((getPageNo().intValue() - 1) * getRecordCount().intValue());
                queryObject.setMaxResults(getRecordCount().intValue());
            }
            List results = queryObject.list();
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List getListByLoginName(String loginName)
    {
        try 
        {
            //2008.7.2 modify
            Query queryObject = getSession().createQuery("from User as model where model.loginName like ? order by model.type desc,model.isSuper desc,model.id");
            queryObject.setParameter(0, "%"+loginName+"%");
            if(this.getPageNo().intValue() > 0 && this.getRecordCount().intValue() > 0)
            {
                queryObject.setFirstResult((getPageNo().intValue() - 1) * getRecordCount().intValue());
                queryObject.setMaxResults(getRecordCount().intValue());
            }
            List results = queryObject.list();
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }
    public int countAllUsersByLoginName(String loginName)
    {
        try 
        {
            Query queryObject = getSession().createQuery("select count(*) from User as model where model.loginName like ?");
            queryObject.setParameter(0, "%"+loginName+"%");
            long longCount = (Long)queryObject.uniqueResult();
            return new Integer(longCount+"");
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    
    public int countAllUsers()
    {
        String queryStr = "select count(*) from User as model";
        Query queryObject = getSession().createQuery(queryStr);
        long longCount = (Long)queryObject.uniqueResult();
        return new Integer(longCount+"");
    }
    
    public void save(User transientInstance) {
        //log.info("saving User instance");
        try {
            getSession().save(transientInstance);
            //log.info("save successful");
        } catch (RuntimeException re) {
            //log.error("save failed", re);
            throw re;
        }
    }
    
    public void update(User transientInstance) {
        //log.debug("update User instance");
        try {
            getSession().update(transientInstance);
            //log.debug("update successful");
        } catch (RuntimeException re) {
            //log.error("update failed", re);
            throw re;
        }
    }
    
	public void delete(User persistentInstance) {
        log.debug("deleting User instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public User findById( java.lang.Integer id) {
        log.debug("getting User instance with id: " + id);
        try {
            User instance = (User) getSession()
                    .get("com.mr.qa.bo.User", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    public List findByExample(User instance) {
        log.debug("finding User instance by example");
        try {
            List results = getSession()
                    .createCriteria("com.mr.qa.bo.User")
                    .add(Example.create(instance))
            .list();
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding User instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from User as model where model." 
         						+ propertyName + "= ?";
         Query queryObject = getSession().createQuery(queryString);
		 queryObject.setParameter(0, value);
		 return queryObject.list();
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByLoginName(Object loginName) {
		return findByProperty(LOGIN_NAME, loginName);
	}
	
	public List findByPassword(Object password) {
		return findByProperty(PASSWORD, password);
	}
	
	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}
	
	public List findBySignature(Object signature) {
		return findByProperty(SIGNATURE, signature);
	}
	
	public List findByMobile(Object mobile) {
		return findByProperty(MOBILE, mobile);
	}
	
	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}
	
	public List findByEmaiExceptId(String email, Integer id){
		try{
			Query queryObject = getSession().createQuery("from User as model where model.id <> :id and model.email = :email");
			queryObject.setParameter("id", id);
			queryObject.setParameter("email", email);
			List results = queryObject.list();
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	public List findByState(Object state) {
		return findByProperty(STATE, state);
	}
	
	public List findByType(Object type) {
		return findByProperty(TYPE, type);
	}
	
    public User merge(User detachedInstance) {
        log.debug("merging User instance");
        try {
            User result = (User) getSession()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(User instance) {
        log.debug("attaching dirty User instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(User instance) {
        log.debug("attaching clean User instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
	public List getUserOrderByAnswerCount(Integer categoryType, Integer returnCount){
		StringBuffer sql = new StringBuffer("select count(a.user_id) cc,a.user_id, u.login_name ")
				.append("from mr_iask_user u, mr_iask_answer a, mr_iask_question q, mr_iask_category c ")
				.append("where a.question_id=q.question_id ")
				.append("and q.category_id=c.category_id ")
				.append("and u.user_id = a.user_id ")
				.append("and c.onlyforadmin = 'N' ")
				.append("and a.is_anonymous = false ")
				.append("and c.state != 1 ")
				.append("and c.type=").append(categoryType).append(" and q.state!=4 ")
				.append("group by a.user_id order by cc desc, user_id asc limit ").append(returnCount);
		Query query = getSession().createSQLQuery(sql.toString());
		//System.out.println(sql);
		return query.list();
	}
}